// 学生
const experss = require("express")
const {
    asyncHandler
} = require("../getSendResult")
const {
    login,
    register,
    checkIn,
    getUp,
    Returns,
    clean,
    Information,
    modifyInfo,
    find,
    payment,
    getIsSignIn,
    getCheckInRecords,
    updataLoginPwd,
    getRoomScope,
    RepairReport
} = require("../../services/StuServ");
const init = require("../../util/init")

const {
    public
} = require("../jwt")
const router = experss.Router()
const multer = require("multer");
const {
    upload
} = require("../../services/CurrServ")
const fs = require('fs');
const path = require("path")

// 权限判定
const checkPermission = require("../checkPermission");

router.all("*", (req, res, next) => {
    checkPermission(req, res, next, [-1])
})
/**
 * 登录
 */
router.post("/login", asyncHandler(async (req, res) => {

    const result = await login(req.body)
    if (result.code === 401) {
        return result
    }
    if (result.state === 2) {
        return result
    } else {
        let token = public(res, undefined, result)
        return {
            state: 1,
            token
        }
    }
}))
/**
 * 注册
 */
router.post('/register', multer().single("avatar"), asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = upload(req.file, async function (filename) {
            const body = {
                ...req.body,
                avatar: filename ? `/upload/${filename}` : `/upload/student.png`
            }
            try {
                const res = await register(body)
                return res;
            } catch (err) {
                throw err
            }
        })
        return reslut;
    })

    return resluts



}))
/**
 * 获取付款二维码
 */
router.get("/getQRCode", asyncHandler(async (req, res) => {

    const reslut = await payment({
        subject: req.query.subject,
        payMoney: +req.query.payMoney,
        peopleNum: +req.query.peopleNum,
        roomNoId: +req.query.roomNoId,
    }, +req.user.id)
    return reslut

}))

/**
 * 获取是否打卡
 */
router.get("/getIsSignIn/:obtainWho", asyncHandler(async (req, res) => {
    const reslut = await getIsSignIn(+req.user.id, +req.params.obtainWho)
    return reslut
}))

/**
 * 获取打卡记录
 */
router.get("/getCheckInRecords", asyncHandler(async (req, res) => {
    const reslut = await getCheckInRecords({
        id: +req.user.id,
        obtainWho: +req.query.obtainWho,
        page: +req.query.page || 1,
        limit: +req.query.limit || 10,
        startingTime: req.query.startingTime || "",
        endTime: req.query.endTime || ""
    })
    return reslut
}))

/**
 * 起床打卡
 */
router.put("/getUp", asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = await getUp(req.user.id)
        return reslut
    })
    return resluts

}))

/**
 * 归宿打卡
 */
router.put("/returns", asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = await Returns(req.user.id)
        return reslut
    })
    return resluts
}))

/**
 * 打扫打卡
 */
router.post("/clean", asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = await clean(req.user.id)
        return reslut
    })
    return resluts
}))

/**
 * 获取学生个人信息
 */
router.get("/Information", asyncHandler(async (req, res) => {
    const reslut = await Information(req.user.id)
    return reslut
}))

/**
 * 修改个人信息
 * 
 */
router.put("/modifyInformation", multer().single("avatar"), asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = upload(req.file, async function (filename) {
            const body = {
                ...req.body,
                avatar: filename ? `/upload/${filename}` : null
            }
            const res = await modifyInfo({
                id: req.user.id,
                studentAvatar: body.avatar,
                phone: body.phone
            })
            return res
        })
        // 删除不需要头像
        if (req.body.oldAvatar && !process.env.DEFAULTAVATAR.includes(req.body.oldAvatar)) {
            fs.unlink(path.resolve(__dirname, "../../public") + req.body.oldAvatar, (err) => {
                if (err) {
                    return err
                }

            })

        }
        return reslut
    })
    return resluts
}))

/**
 * 找回学生密码
 */
router.put("/find", asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = await find(req.body)
        return reslut
    })
    return resluts
}))

/**
 * 修改密码
 */
router.put("/updataLoginPwd", asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = await updataLoginPwd({
            id: req.user.id,
            oldLoginPwd: req.body.oldLoginPwd,
            newLoginPwd: req.body.newLoginPwd,
            confirmLoginPwd: req.body.confirmLoginPwd
        })

        return reslut
    })
    return resluts

}))

/**
 * 入住
 */
router.post("/checkIn", asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const resulet = await checkIn({
            stuIofnId: +req.user.id,
            OrderNo: req.body.OrderNo,
            dormitoryId: +req.body.dormitoryId,
            floorID: +req.body.floorID,
            roomNoId: +req.body.roomNoId,
            bednumberId: +req.body.bednumberId
        })
        return resulet
    })
    return resluts

}))
/**
 * 获取可以选择的宿舍
 */
router.get("/getRoomScope", asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = await getRoomScope(req.user.id)
        return reslut
    })
    return resluts
}))

/**
 * 报修
 */
router.post("/RepairReport", multer().single("avatar"), asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = upload(req.file, async function (filename) {
            const body = {
                RoomId: +req.body.RoomId || null,
                avatar: filename ? `/upload/${filename}` : null,
                describe: req.body.describe || null,
                RepariDormitroy: req.body.RepariDormitroy || null,
                RepariFloor: req.body.RepariFloor || null,
                RepariRoomNo: req.body.RepariRoomNo || null
            }
            const res = await RepairReport(body)
            return res
        })
        return reslut
    })
    return resluts
}))


module.exports = router;